#include "detrendrr.h"
#include "qdebug.h"

DetrendRR::DetrendRR() {}

// QMF函数实现
QVector<double> DetrendRR::qmf(const QVector<double>& x, int p) {
    // 参数检查
    if (p != static_cast<int>(p) || p < 0) {
        qDebug() << "Invalid argument value for p.";
        return QVector<double>();
    }
    // 反转向量
    QVector<double> y = x;
    std::reverse(y.begin(),  y.end());

    // 根据p的值改变符号
    int first = 2 - (p % 2);
    for (int i = first - 1; i < y.size();  i += 2) {
        y[i] = -y[i];
    }

    return y;
}

// 翻转函数
QVector<double> DetrendRR::flip(const QVector<double>& x) {
    QVector<double> y = x;
    std::reverse(y.begin(),  y.end());
    return y;
}
// ORTHFILT函数
void DetrendRR::orthfilt(const QVector<double>& W, int P, QVector<double>& Lo_D, QVector<double>& Hi_D, QVector<double>& Lo_R, QVector<double>& Hi_R) {
    // 归一化滤波器
    double sumW = 0.0;
    for (double val : W) {
        sumW += val;
    }
    QVector<double> normalizedW = W;
    for (double& val : normalizedW) {
        val /= sumW;
    }

    // 计算低通和高通滤波器
    Lo_R = normalizedW;
    for (double& val : Lo_R) {
        val *= std::sqrt(2);
    }

    Hi_R = qmf(Lo_R, P);
    Hi_D = flip(Hi_R);
    Lo_D = flip(Lo_R);
}
